package com.alpesressources.comexpert.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alpesressources.comexpert.bo.Token;

public class TokenBase {
	private static TokenBase instance = new TokenBase();
	private Map<String, Token> tokens;

	public static TokenBase getInstance() {
		return instance;
	}

	private TokenBase() {
		tokens = new HashMap<String, Token>();
	}

	public boolean isValid(String token, String remoteAddr) {
		if (tokens.containsKey(token)) {
			Token t = tokens.get(token);
			if (!t.getRemoteAddr().equals(remoteAddr)
					|| t.getExpireDate().before(new Date())) {
				tokens.remove(token);

				return false;
			}

			return true;
		}

		return false;
	}

	public void create(String token, String remoteAddr) {
		if (!tokens.containsKey(token)) {
			Calendar c = Calendar.getInstance();
			Token t = new Token();

			c.add(Calendar.DATE, 1);

			t.setToken(token);
			t.setRemoteAddr(remoteAddr);
			t.setExpireDate(c.getTime());

			tokens.put(token, t);
		}
	}
}
